
from background import BackGround
from player import Player
from controller import Controller
from Cube.map import QMapBody
from Cube.game import ObjectPoolGet
from Cube.map import QMemberType
from Command import CMD_CHECKER

class SampleMapBody(QMapBody):
    def Initialize(self):
        print "SampleMapBody.Initialize"
        BackGround()  # back ground

        # create players
        self.Players = {}
        for memberEntry in self.MemberList:
            if memberEntry.CurrentMemberType in \
              [QMemberType.HUMAN, QMemberType.COMPUTER]:
                self.Players[memberEntry.MemberID] = Player(memberEntry)
        # create controller
        self.Controller = Controller()

        #self.updateCnt = 0

        #print ObjectPoolGet()
        # must call this function when initialize finished
        self.InitializeDone()

    def CmdHandle(self, memberID, param):
        #print "SampleMapBody.CmdHandle", param
        # sync-checking
        if (param[0] == CMD_CHECKER) and (not self.AmIServer):
            syncData = param[1]
            for (memberID, pos) in syncData.items():
                self.SyncCheck(memberID, pos)
        else:
            # input cmd
            self.Players[memberID].CmdHandle(param)

    def CmdExecDoneHandler(self, CmdDispatchPeriods):
        # insert more update
        #print "SampleMapBody.CmdExecDoneHandler: ", self.updateCnt
        #self.updateCnt += 1
        self.LogicUpdate(CmdDispatchPeriods)

    def LogicUpdate(self, periods):
        for player in self.Players.itervalues():
            player.LogicUpdate(periods)

        # sync-checking
        if self.AmIServer:
            syncData = {}
            for player in self.Players.itervalues():
                syncData[player.MyInfo.MemberID] = player.Ship.PosGet()
            self.CmdSend((CMD_CHECKER, syncData))

    def SyncCheck(self, memberID, syncPos):
        curPos = self.Players[memberID].Ship.PosGet()
        if (curPos != syncPos):
            print "Sync Fail: current pos = %s, sync pos =%s"%(curPos,syncPos)
